﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
using System.IO;
using EmbeddedSharp.Core;

namespace EmbeddedSharp.Scripting.Function {

    /// <summary>
    /// help("fib");
    /// </summary>
    public class HelpNode : ContextFuncNode {

        public HelpNode() {
            base.Value = "help";
        }

        public override object Evaluate() {
            if (Parameters.Count == 0) {
                throw new ArgumentException("Usage: help(funcName)");
            }

            string comment = string.Empty;
            string funcName = Convert.ToString(Parameters[0].Evaluate());

            FuncNode func = DefaultDependencyManager.Instance.FunctionManager.GetFunction(funcName);
            if (func == null) {
                return (
                    "No availble information for " + funcName);
            } else {
                if (func is UserDefinedFunctionNode) {
                    UserDefinedFunctionNode udf
                        = func as UserDefinedFunctionNode;
                    comment = udf.Comment;
                } else {
                    FunctionAttribute fa = this.Context.GetFunctionManager().GetFunctionAttribute(funcName);
                    comment = fa.Description;
                }
                if (string.IsNullOrEmpty(comment)) {
                    return ("The function was found but there is no comment left.");
                } else {
                    return (comment);
                }
            }
        }

        protected string FindHelp(FuncNode func) {
            string help = ConfigurationManager.AppSettings["fhelp"];
            string[] lines = File.ReadAllLines(help);

            foreach (string line in lines) {
                string[] c = line.Split('=');
                if (c[0].Trim() == func.Value) {
                    return c[1];
                }
            }

            return string.Empty;
        }
    }
}
